package lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;


/**
 * Java 锁的实现方式, 比较? AQS实现原理?公平非公平实现原理?
 * ReentrantLock 默认非公平锁
 *
 * @author jiangwz
 * @create 2019/8/28.
 */
public class LockTest {

    ReentrantLock lock = new ReentrantLock();

    private int count;

    public void noLock(){
        System.out.println("count =" + ++count);
    }
    public synchronized void lock(){
        System.out.println("count =" + ++count);
    }
    public  void reentrantLock() {
        lock.lock();
        System.out.println("count =" + ++count);
        lock.unlock();
    }

    public void testInterrupt(){

        try {
            lock.tryLock(1, TimeUnit.SECONDS);
            System.out.println("lock");
            TimeUnit.SECONDS.sleep(10);
            System.out.println("end");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("unlock");
            lock.lock();
        }

    }

    public static void main(String[] args) throws InterruptedException {
        LockTest test = new LockTest();

        // 不加锁可能会出现重复的数
//        for (int i = 0; i < 100; i++) {
//            new Thread(() -> test.noLock()).start();
//        }

        // 加synchronized 锁后一切正常
//        for (int i = 0; i < 100; i++) {
//            new Thread(() -> test.lock()).start();
//        }

        // 也一切正常
//        for (int i = 0; i < 100; i++) {
//            new Thread(() -> test.reentrantLock(),"jwz-" + i).start();
//        }

        Thread thread = new Thread(() -> test.testInterrupt());
        thread.start();
        TimeUnit.SECONDS.sleep(5);
        thread.interrupt();
    }


}
